var hprose = require('./../lib/hprose/hprose');
var self = null;
var server = null;

function call(json, callback) {
	try {
		if (!json.route || !json.action) return callback("hp service call format error");
		self.interface_callback(json.route, json.action, json.params, (result) => {
			if (typeof result === "object"){
				let i = 0;
				for (let x in result) i++;
				if (i == 0) result = null;
			}
			callback(result);
		});
	}catch (e){
		console.log("hp service call error:" + e + "\n json:" + JSON.stringify(json));
		callback("" + e);
	}
}

function start_server() {
	server = hprose.Server.create(self.config.agreement + "://0.0.0.0:" + self.config.port);
	server.addAsyncFunction(call);
	server.onSendError = function (error, context) {};
	server.onAccept = function (context) {};
	if (self.config.publish) server.publish('push');
	server.start();
}

module.exports = {
	config: null,
	interface_callback: null,   //  接口回调
	error_callback: null,   //  异常时回调 fn(message)
	start:function (config, interface_callback) {
		try{
			self = this;
			self.config = config;
			if (!self.config.enable) return;
			self.interface_callback = interface_callback;
			start_server();
			console.log("hp service start port:" + self.config.port);
		}catch (e){
			console.error("hp service start error:" + e);
		}
	},
	push:function (action, obj) {
		try{
			if (!self.config.enable) return;
			server.broadcast("push", {action: action, params:obj});
		}catch (e){
			console.log("hp service push msg error:" + e);
		}
	}
};